package cloud.seri.gateway.security.oauth2

import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.springframework.http.HttpMethod
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.security.oauth2.common.OAuth2AccessToken

/**
 * Test whether the [CookieTokenExtractor] can properly extract access tokens from
 * Cookies and Headers.
 */
class CookieTokenExtractorTest {

    private lateinit var cookieTokenExtractor: CookieTokenExtractor

    @Before
    fun init() {
        cookieTokenExtractor = CookieTokenExtractor()
    }

    @Test
    fun testExtractTokenCookie() {
        val request = OAuth2AuthenticationServiceTest.createMockHttpServletRequest()
        val authentication = cookieTokenExtractor.extract(request)
        Assert.assertEquals(OAuth2AuthenticationServiceTest.ACCESS_TOKEN_VALUE, authentication.principal.toString())
    }

    @Test
    fun testExtractTokenHeader() {
        val request = MockHttpServletRequest(HttpMethod.GET.name, "http://www.test.com")
        request.addHeader("Authorization", OAuth2AccessToken.BEARER_TYPE + " " + OAuth2AuthenticationServiceTest.ACCESS_TOKEN_VALUE)
        val authentication = cookieTokenExtractor.extract(request)
        Assert.assertEquals(OAuth2AuthenticationServiceTest.ACCESS_TOKEN_VALUE, authentication.principal.toString())
    }

    @Test
    fun testExtractTokenParam() {
        val request = MockHttpServletRequest(HttpMethod.GET.name, "http://www.test.com")
        request.addParameter(OAuth2AccessToken.ACCESS_TOKEN, OAuth2AuthenticationServiceTest.ACCESS_TOKEN_VALUE)
        val authentication = cookieTokenExtractor.extract(request)
        Assert.assertEquals(OAuth2AuthenticationServiceTest.ACCESS_TOKEN_VALUE, authentication.principal.toString())
    }
}
